package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.vo.DishVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Log4j2
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;

    @Autowired
    DishFlavorService dishFlavorService;

    @Override
    public List<Dish> findCategoryById(ArrayList<Long> ids) {
        return dishMapper.findCategoryById(ids);
    }

    @Override
    @Transactional
    public Result addDish(DishDTO dishDTO) {
        Dish dish = Dish.builder().build();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.addDish(dish); // 插入菜品

        List<DishFlavor> dishFlavors = dishDTO.getFlavors().stream()
                .map(flavor -> flavor.setDishId(dish.getId()))
                .collect(Collectors.toList());
        dishFlavorService.addFlavorService(dishFlavors); // 插入口味
        return Result.success();
    }

    @Autowired
    CategoryService categoryService;

    @Override
    public PageResult queryPage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<Dish> page = dishMapper.queryPage(dishPageQueryDTO);
        long total = page.getTotal();
        List<Dish> dishes = page.getResult();
        List<DishVO> collect = dishes.stream().map(dish -> {
            String name = categoryService.findDishCateGoryById(dish.getCategoryId()).getName();
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setCategoryName(name);
            return dishVO;
        }).collect(Collectors.toList());
        return new PageResult(total, collect);
    }

    @Override
    public List<Dish> findDishCateGoryById(Long categoryId) {
        return dishMapper.findDishCateGoryById(categoryId);
    }

    @Override
    public void statusDish(Integer status, Long id) {
        Dish dish = Dish.builder().status(status).id(id).build();
        dishMapper.updateDish(dish);
    }


    @Override
    public DishVO queryDishById(Long id) {
        Dish dish = dishMapper.queryDishById(id);
        DishVO dishVO = DishVO.builder().build();
        BeanUtils.copyProperties(dish, dishVO);
        Category category = categoryService.findDishCateGoryById(dish.getCategoryId());
        List<DishFlavor> dishFlavor = dishFlavorService.findflavorByDishId(id);
        dishVO.setFlavors(dishFlavor);
        dishVO.setCategoryName(category.getName());
        return dishVO;
    }

    @Override
    @Transactional
    public void putDish(DishDTO dishDTO) {
        // 更新菜品表
        Dish dish = Dish.builder().build();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateDish(dish);
        // 口味表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        List<DishFlavor> collect = flavors.stream().map(flavor -> flavor.setDishId(dish.getId())).collect(Collectors.toList());
        dishFlavorService.updateFlavor(collect);

    }

    @Autowired
    SetmealDishService setmealDishService;

    @Override
    @Transactional
    public String delDishByIds(List<Long> ids) {
        // 判断是否有起售菜品，起售中的菜品不允许删除
        List<Dish> dishes = dishMapper.findDishCateGoryByIds(ids);
        // 起售的菜品
        List<Dish> enableDish = dishes.stream().filter(dish -> dish.getStatus() == StatusConstant.ENABLE).collect(Collectors.toList());
        // 未起售的菜品
        List<Dish> idsableDish = dishes.stream().filter(dish -> dish.getStatus() == StatusConstant.DISABLE).collect(Collectors.toList());

        if(!idsableDish.isEmpty()){
            // 获取未起售的菜品ids
            List<Long> ableDishIds = idsableDish.stream().map(id -> id.getId().longValue()).collect(Collectors.toList());

            // DUTO判断当前菜品是否被套餐关联了
            List<SetmealDish> setmealDishs = setmealDishService.findSetmealDishByDishIds(ableDishIds);
            if(setmealDishs.isEmpty()){
                // 删除菜品关联的口味
                List<DishFlavor> dishFlavors = ableDishIds.stream().map(id -> DishFlavor.builder().dishId(id).build()).collect(Collectors.toList());
                dishFlavorService.delAllFlavorsById(dishFlavors);
                // 删除菜品名单
                dishMapper.delDishByIds(ableDishIds);
                log.info("删除成功");
                return "菜品未被套餐关联，删除成功";
            }else {
                log.info("部分菜品删除成功, 部分当前菜品关联了套餐,不能删除");

                return "部分菜品删除成功, 部分当前菜品关联了套餐,不能删除";
            }
        }else {
            log.info("部分菜品删除成功, 部分当前菜品为起售状态，不能删除");
            System.out.println(enableDish);
//            throw new DeletionNotAllowedException("部分菜品删除成功, 部分当前菜品为起售状态，不能删除");
            return "部分菜品删除成功, 部分当前菜品为起售状态，不能删除" + enableDish;
        }
    }

    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
